import { defineStore } from 'pinia';

export const useTabStore = defineStore('tabs', {
  state: () => ({
    // 存储所有打开的标签页
    openedTabs: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/home.vue'),
        meta: {
          title: '首页',
          icon: 'HomeFilled',
          requireAuth: true,
        },
      },
    ],
    // 当前激活的标签页
    activeTab: '/home',
  }),

  getters: {
    // 获取所有打开的标签页的路径
    openedTabPaths(state) {
      return state.openedTabs.map((tab) => tab.path);
    },
  },

  actions: {
    // 添加一个新的标签页
    addTab(tab) {
      if (!this.openedTabPaths.includes(tab.path) && tab.name !== 'notFound') {
        this.openedTabs.push(tab);
      }
      this.setActiveTab(tab.path);
    },

    // 移除一个标签页
    removeTab(path) {
      this.openedTabs = this.openedTabs.filter((tab) => tab.path !== path);
      if (path === this.activeTab) {
        // 如果关闭的是当前激活的标签页，则激活最后一个标签页
        const lastTab = this.openedTabs[this.openedTabs.length - 1];
        if (lastTab) {
          this.setActiveTab(lastTab.path);
        }
      }
    },

    // 设置当前激活的标签页
    setActiveTab(path) {
      if (this.openedTabPaths.includes(path)) {
        this.activeTab = path;
      }
    },

    // 关闭其他标签页
    closeOtherTabs(path) {
      this.openedTabs = this.openedTabs.filter((tab) => tab.path === path || tab.path === '/home');
      this.setActiveTab(path);
    },

    // 关闭所有标签页
    closeAllTabs() {
      this.openedTabs = this.openedTabs.filter((tab) => tab.path === '/home');
      this.setActiveTab('/home'); // 默认激活首页
    },
  },
});
